import axios from 'axios'
import qs from 'qs'
import router from '../router'
import { Toast } from 'vant'
import Vue from 'vue'
// 创建一个新实例
const vm = new Vue()
const request = axios.create({
  baseURL: '/conner'
})
const upload = axios.create({
  baseURL: '/conner',
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})
Vue.prototype.upload = upload
request.interceptors.request.use(function (config) {
  if (config.method === 'post' && config.data) {
    config.data = qs.stringify(config.data)
  }
  vm.$showLoading()
  return config
}, function (error) {
  vm.$closeLoading()
  return Promise.reject(error)
})

request.interceptors.response.use(function (response) {
  if (response.data.code === 2000) {
    Toast({
      type: 'fail',
      message: response.data.msg,
      onClose: () => {
        localStorage.removeItem('token')
        router.push('/login')
      }
    })
  }
  vm.$closeLoading()
  return response
}, function (error) {
  vm.$closeLoading()
  return Promise.reject(error)
})

export default request
